#include "elementimage.h"
#include "exceptions.h"

ElementImage::ElementImage()
{
    bufferImage = NULL;
    image = new FluffyImage();
}

ElementImage::~ElementImage()
{
    //Удаляем буфер изображения
    if (bufferImage)
        delete bufferImage;

    //Удаляем векторное изображение
    delete image;
}

void ElementImage::create(int width, int height)
{
    if (image)
        delete image;
    image = new FluffyImage(width, height);
}

void ElementImage::load(const QDomNode& node)
{
    image = new FluffyImage(node.toElement());
}

void ElementImage::paintToBuffer(qreal scale)
{
    if ((scale < 0.2) || (scale > 5.0))
        throw GenericException(tr("Invalid scale for image"));
    if (scaleImage != scale)
    {
        scaleImage = scale;
        if (bufferImage)
            delete bufferImage;
        bufferImage = new QImage(image->getWidth(),image->getHeight(),
                                            QImage::Format_ARGB32_Premultiplied);
        bufferImage->fill(0);
        image->draw(bufferImage,scaleImage);
        emit onPaint(bufferImage,scaleImage);
    }
}

QImage* ElementImage::getBufferImage()
{
    //Если изображения не существует, то отрисовываем в масштабе 1.0
    if (!bufferImage)
        paintToBuffer(1.0);
    return this->bufferImage;
}

void ElementImage::refresh()
{
    emit refresh();
    paintToBuffer(scaleImage);
}

qreal ElementImage::getScale()
{
    return scaleImage;
}
